<template>
  <div ref="layerWatermarkModal" v-if="visible">
    <a-modal class="modal-warpper" :getContainer="() => $refs.layerWatermarkModal" centered :visible="visible" :title="title" width="760px" @ok="handleOk" @cancel="handleCancel" :ok-text="okText">
      <a-row :gutter="36">
        <a-col :span="12">
          <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="dyRef" />
        </a-col>
        <a-col :span="12">
          <div class="canvas-title">预览</div>
          <div id="rotate" class="h-111.5 border border-gray-200 shadow-md rounded-md relative">
            <span class="span-angle left-7.5 top-5">┘</span>
            <span class="span-angle right-7.5 top-5">└</span>
            <span class="span-angle left-7.5 bottom-5">┐</span>
            <span class="span-angle right-7.5 bottom-5">┌</span>
            <img v-if="imageURL" :src="imageURL" alt="Image with Watermark" />
          </div>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, getCurrentInstance, onMounted, ref, watch } from 'vue';
import { DynamicForm } from '@/components/public-template';
import { formInfoStore } from '@/store/modules/form';
import indexService from './addDialog.service';
import watermark from 'watermarkjs';
import { useUserStoreWithOut } from '@/store/modules/user';
import { Api, watermarkSave } from '@/config/api/watermark';
import { message } from 'ant-design-vue';
import { RESETTABLE } from '@/mixins/subject/subject-types';
import { throttle } from 'xe-utils';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  showType: {
    type: String
  },
  data: {
    type: Object
  }
});
const emit = defineEmits(['update:visible', 'update:showType', 'handleEdit']);
const TITLE = {
  ADD: '添加电子水印',
  VIEW: '电子水印详情',
  EDIT: '编辑电子水印'
};
const OK_TEXT = {
  ADD: '确定',
  VIEW: '编辑',
  EDIT: '确定'
};
const title = computed(() => TITLE[props.showType]);
const okText = computed(() => OK_TEXT[props.showType]);
const dyRef = ref(null);
const imageURL = ref(null);
const { proxy }: any = getCurrentInstance();
const dyConfig: any = {
  id: props.data?.id,
  queryUrl: `${Api.watermarkGet}/${props.data?.id}`,
  labelCol: 8,
  wrapperCol: 24,
  layout: 'vertical',
  cancelSave: true
};
const formStore = formInfoStore();
formStore.setQuestions(props.showType == 'VIEW' ? indexService.getViewQuestions() : indexService.getQuestions(props.showType));
const dyQuestions = formStore.getQuestions;
onMounted(() => {
  // form数据监听，重新绘制水印
  watch(
    () => dyRef.value.getDataFrom(),
    () => drewWatermark()
    // { immediate: true }
  );
});
// 水印绘制
function drewWatermark() {
  console.log('触发 drewWatermark');
  watermark([])
    .image(rotate)
    .then(function (img) {
      imageURL.value = img.src;
    });
}
// 获取水印
function rotate() {
  const formData = dyRef.value.getDataFrom();
  console.log('formData', formData);
  const target = getCanvas();
  const textCanvas = document.createElement('canvas');
  // 字体宽高，水印间距 拉伸/平铺
  textCanvas.width = formData.contentType == 1 ? target.width : formData.acrossGap;
  textCanvas.height = formData.contentType == 1 ? target.height : formData.standGap;
  if (!textCanvas.width || !textCanvas.height) return target;
  // 自定义内容
  const userStore = useUserStoreWithOut();
  const loginInfo: any = userStore.getLoginInfo;
  const text = formData.type == 1 ? formData.customizeContent || '' : formData.type == 2 ? `${loginInfo.phone} ${loginInfo.nickName || ''}` : '';
  const context = textCanvas.getContext('2d');
  const metrics = context.measureText(text);
  // const x = target.width / 2 - (metrics.width + 24);
  // const y = target.height / 2 + 48 * 2;
  const x = textCanvas.width / 2;
  const y = textCanvas.height / 2;
  context.translate(x, y);
  // 透明度
  context.globalAlpha = formData.transparency / 100;
  // 字体
  context.font = `${formData.fontSize}px sans-serif`;
  context.fillStyle = '#000';
  // 水平垂直居中
  context.textAlign = 'center';
  context.textBaseline = 'middle';
  // 角度
  let ANGLE = {
    1: -90,
    2: 0,
    3: -45,
    4: 45
  };
  context.rotate((-parseInt(ANGLE[formData.angle]) * Math.PI) / 180);
  context.fillText(text, 0, 0);

  const ctx = target.getContext('2d');
  const pat = context.createPattern(textCanvas, formData.contentType == 1 ? 'no-repeat' : 'repeat'); // 不重复/重复
  ctx.fillStyle = pat;
  ctx.fillRect(0, 0, target.width, target.height);
  return target;
}

// 获取矢量图
function getCanvas() {
  const width = 334;
  const height = 446;
  // 创建一个canvas画布
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  return canvas;
}
const handleOk = throttle(function () {
  if (props.showType == 'ADD') {
    dyRef.value.isValidateFields().then(() => {
      const data = dyRef.value.getDataFrom();
      watermarkSave(data).then((result) => {
        if (result.success) {
          message.success('添加成功');
          proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'watermarkTable' } });
          emit('update:visible', false);
        }
      });
    });
  } else if (props.showType == 'VIEW') {
    emit('handleEdit', props.data);
  } else if (props.showType == 'EDIT') {
    dyRef.value.onFinish((params) => {
      watermarkSave(params).then((result) => {
        if (result.success) {
          message.success('修改成功');
          proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'watermarkTable' } });
          emit('update:visible', false);
        }
      });
    });
  } else {
    emit('update:visible', false);
  }
}, 3000);
function handleCancel() {
  emit('update:visible', false);
}
</script>

<style lang="less" scoped>
.span-angle {
  font-size: 20px;
  font-family: fangsong;
  @apply text-gray-200 absolute;
}
.canvas-title {
  font-size: 20px;
  color: rgba(0, 0, 0, 0.65);
}
</style>
